import axios from 'axios'
import { ElMessage } from 'element-plus'
import 'element-plus/es/components/message/style/css'
import { getToken, removeToken, setToken } from '@/store/cookie/cookie'
import store from '@/store'

const baseUrl = '/api'
const service = axios.create({
  baseURL: baseUrl
  // withCredentials: true
})
// 请求拦截器
service.interceptors.request.use((config) => {
  config.headers.Authorization = getToken()
  return config
}, (err) => {
  return err
})

// 响应拦截器
service.interceptors.response.use((response) => {
  const res = response.data
  // console.log(response.headers.Authorization)
  if (response.headers.hasOwnProperty.call('Authorization')) {
    res.token = response.headers.Authorization
    setToken(response.headers.Authorization)
    store.dispatch('set_token')
  }
  return response.data
}, (error) => {
  const response = error.response
  const data = response.data
  if (response.data.code === 401) {
    removeToken()
    store.dispatch('del_token')
  }
  ElMessage({
    showClose: true,
    message: data.message,
    grouping: true,
    type: 'error'
  })
  return error
})

export default service
